package dataBase

import (
	"encoding/json"
	"fmt"
	"log"
	. "myTaxServer/src/structs"
	. "myTaxServer/src/tools"
)

func FindUserInfo(openid string) ReturnUserInFo { //返回userinfo表的id
	rows, err := Db.Query("SELECT Id FROM userinfo where OpenId = ?",openid); //从unionuserinfo表中查询oponid
	if err != nil {                                                           //如果是空的话打印错误信息
		log.Fatalln(err);
	}
	rowsb, err := Db.Query("SELECT Nickname FROM unionuserinfo where OpenId = ?",openid); //从unionuserinfo表中查询oponid
	if err != nil {                                                                       //如果是空的话打印错误信息
		log.Fatalln(err);
	}
	defer rows.Close();//推迟关闭
	defer rowsb.Close();
	var userinfoId ReturnUserInFo;
	for rows.Next() {
		rows.Scan(&userinfoId.Id);
	}
	for rowsb.Next() {
		rowsb.Scan(&userinfoId.Nickname);
	}
	fmt.Println(userinfoId)
	return userinfoId;
}

func checkIsSigned(openid string)  int64{//查看是否已经注册了
	fmt.Println("需要校验的数据为："+openid)
	rows, err := Db.Query("SELECT openId FROM userinfo where openId = ?",openid); //从unionuserinfo表中查询oponid
	rowsu, err := Db.Query("SELECT openId FROM unionuserinfo where openId = ?",openid);
	if err != nil {//如果是空的话打印错误信息
		log.Fatalln(err);
	}
	defer rows.Close();//推迟关闭
	openIds := make([]string,0);
	openIdsu := make([]string,0);
	for rows.Next() {
		var tempdata string;
		rows.Scan(&tempdata);
		openIds = append(openIds, tempdata);//将处理好的数据添加到切片persons
	}
	for rowsu.Next() {
		var tempdatau string;
		rows.Scan(&tempdatau);
		openIdsu = append(openIdsu, tempdatau);//将处理好的数据添加到切片persons
	}
	//fmt.Println(len(openIds))
	//lens := len(openIds)
	if err = rows.Err(); err != nil {//打印错误信息
		log.Fatalln(err);
	}
	if len(openIds)==len(openIdsu)&&len(openIdsu)==0 {
		return 1;
	}
	return 0;
}

func InsertUserInfo(strr WxUserInfo,sessionkey string)  {
	id := GenerateId();
	idb := GenerateId();
	CreatorId := 0;
	CreatorIp := "172.0.0.1";
	Creator := "system";
	//储存到数据库
	if(checkIsSigned(strr.OpenID)==1){
		fmt.Println("数据未存在，正在插入");
		err, _ := Db.Exec("INSERT INTO unionuserinfo(UserInfoId,AvatarUrl,City,Country,Gender,Nickname,Province,OpenId,UnionId,Id,SessionKey,CreatorId,CreatorIp,Creator) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",idb, strr.AvatarURL,strr.City,strr.Country,strr.Gender,strr.NickName,strr.Province,strr.OpenID,strr.UnionID,id,sessionkey,CreatorId,CreatorIp,Creator);
		err2,_ := Db.Exec("INSERT INTO userinfo(OpenId,Id,CreatorId,CreatorIp,Creator) VALUES (?,?,?,?,?)", strr.OpenID,idb,CreatorId,CreatorIp,Creator);
		if err == nil|| err2 == nil{
			fmt.Println("插入失败")
		}
		fmt.Println("已插入成功")
	}else {
		println("数据已经存在")
	}
}

func isSame (datas MoneyData,index int) int{
	fmt.Println("index")
	fmt.Println(index)
	if index == 0{
		return 1;
	}else{
		fmt.Println("index!=0")
		indext := index-1;
		if datas.Sqsy[index] == datas.Sqsy[indext] && datas.Wxyj[index].Gjjbase == datas.Wxyj[indext].Gjjbase && datas.Wxyj[index].Gjj == datas.Wxyj[indext].Gjj  && datas.Wxyj[index].Sb == datas.Wxyj[indext].Sb && datas.Wxyj[index].Sbbase == datas.Wxyj[indext].Sbbase {
			return 1;
		}else {
			return 0;
		}
	}
	return 1;
}

func StorageUserDatas(datas MoneyData,temp [12]ReturnStyle,ip string)  int64{
	tempUserInfo := FindUserInfo(datas.OpenId); //读取openid
	userinfoId := tempUserInfo.Id;
	Creator := tempUserInfo.Nickname;
	println("userinfoId为")
	println(userinfoId)
	userqueryId := GenerateId();
	stringDatas,_:= json.Marshal(datas)
	Db.Exec("INSERT INTO userquery(Id,UserInfoId,QueryType,QueryCondition,CreatorId,CreatorIp,Creator) VALUES (?,?,?,?,?,?,?)", userqueryId,userinfoId,datas.QueryType,stringDatas,userinfoId,ip,Creator);
	//lastSalary,last,lastHousingFundBase,lastHousingFundRate,lastSocialFundBase,lastSocialFundRate,monthbegin,monthend:= 0,0,0,0,0,0,0,0;
	monthbegin:= 1;
	for i:=0;i<12;i++{
		t := i;
		//如果和上个月不一样的话
		resultId := GenerateId();
		Db.Exec("INSERT INTO userqueryresult(Id,UserQueryId,MonthIndex,Salary,SocialFund,SpecialDeduction,SalaryForTax,SalaryActually,HousingFund,SalaryForTaxAccumulation,Tax,CreatorId,CreatorIp,Creator) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",resultId,userqueryId,i+1,temp[i].Sqsr,temp[i].Wxyj,temp[i].Zxkc,temp[i].Ynssd,temp[i].Shxz,temp[i].Zfgjj,temp[i].Ljynssd,temp[i].Grsd,userinfoId,ip,Creator);
		if isSame(datas,t)==0||t==11 {
			if t==11{
				t=12;
			}
			userquerydetailId := GenerateId();
			//db.Exec("INSERT INTO userquerydetails(Id,UserQueryId,Salary,SelfEducation,SeriousIllness,HousingLoanInterest,HousingRent,ParentsSupport,MonthBegin,MonthEnd,HousingFundBase,HousingFundRate,SocialFundBase,SocialFundRate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",userquerydetailId,userqueryId,datas.Sqsy[t-1],datas.Jxjy,datas.Dbyl,datas.Zffd,datas.Zfzj,datas.Sylr,monthbegin,t,datas.Wxyj[t-1].Gjjbase,datas.Wxyj[t-1].Gjj,datas.Wxyj[t-1].Sbbase,datas.Wxyj[t-1].Sb);
			Db.Exec("INSERT INTO userquerydetails(Id,UserQueryId,MonthBegin,MonthEnd,Salary,HousingFundBase,HousingFundRate,SocialFundBase,SocialFundRate,ChildrenCount,SelfEducation,SeriousIllness,HousingLoanInterest,HousingRent,SiblingsCount,ChildrenEducation,ParentsSupport,CreatorId,CreatorIp,Creator) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",userquerydetailId,userqueryId,monthbegin,t,datas.Sqsy[t-1],datas.Wxyj[t-1].Gjjbase,datas.Wxyj[i].Gjj,datas.Wxyj[i].Sbbase,datas.Wxyj[i].Sb,datas.Znjy,datas.Jxjy,datas.Dbyl,datas.Zffd,datas.Zfzj,datas.Sylr,datas.Cdjy,datas.Ywlr,userinfoId,ip,Creator);
			fmt.Println("已经插入成功")
			monthbegin = i + 1;
		}
	}
	return userqueryId;
}

func FindHistory(openid string)  []ReturnHistorystruct{
	userInfoId := FindUserInfo(openid).Id;//查找用户的id
	rows,err := Db.Query("SELECT Id ,QueryType ,CreateTime ,QueryCondition FROM userquery where UserInfoId = ?",userInfoId);
	if err != nil {//如果是空的话打印错误信息
		log.Fatalln(err);
	}
	defer rows.Close();//推迟关闭-
	usershistory :=make([]ReturnHistorystruct,0);
	var tempusershistory ReturnHistorystruct;
	for rows.Next(){
		totalt := 0.0;
		total := 0.0;
		rows.Scan(&tempusershistory.Id,&tempusershistory.QueryType,&tempusershistory.CreateTime,&tempusershistory.QueryCondition);
		rowsb,_ := Db.Query("SELECT SalaryActually FROM userqueryresult where UserQueryId = ?",tempusershistory.Id);
		for rowsb.Next(){
			rowsb.Scan(&totalt);
			total +=Decimal(totalt);
		}
		fmt.Println(tempusershistory.Id)
		tempusershistory.Total = Decimal(total);
		usershistory = append(usershistory,tempusershistory);
	}
	return usershistory
}

func FindResult(userQueryId string)  []HistoryResultStruct{
	var temp HistoryResultStruct;
	returnDatat := make([]HistoryResultStruct,0);
	rows,_ := Db.Query("SELECT MonthIndex,Salary,HousingFund,SocialFund,SpecialDeduction,SalaryForTax,SalaryActually,SalaryForTaxAccumulation,Tax FROM userqueryresult where UserQueryId = ?",userQueryId);
	for rows.Next(){
		rows.Scan(&temp.MonthIndex,&temp.Salary,&temp.HousingFund,&temp.SocialFund,&temp.SpecialDeduction,&temp.SalaryForTax,&temp.SalaryActually,&temp.SalaryForTaxAccumulation,&temp.Tax);
		returnDatat = append(returnDatat,temp);
		fmt.Println(temp)
	}
	if(returnDatat[0].SalaryForTaxAccumulation > returnDatat[1].SalaryForTaxAccumulation){
		returnData := make([]HistoryResultStruct,0);
		for i:=11;i>=0;i--{
			returnData = append(returnData,returnDatat[i]);
		}
		return returnData;
	}else {
		return returnDatat;
	}
}